package com.example.asus.get_postdemo;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by asus on 2017/11/21.
 */

public class RequestUtil {

    private RequestUtil() {
    }

    public enum Method {GET, POST}


    private static RequestUtil requestUtil;

    public static RequestUtil getInstance() {

        if (requestUtil == null) {
            synchronized (RequestUtil.class) {
                if (requestUtil == null) {
                    requestUtil = new RequestUtil();
                }
            }
        }

        return requestUtil;
    }

    public String Login(Method method, String username, String password) throws IOException {
        if (method == Method.GET) {
            URL url = new URL("http://172.17.136.88:8080/login/login?username=" + username + "&pwd=" + password + "");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            if (httpURLConnection.getResponseCode() != 200) {
                return null;
            }
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String result = bufferedReader.readLine();
            httpURLConnection.disconnect();
            return result;
        }

        if (method == Method.POST) {
            URL url = new URL("http://172.17.136.88:8080/loginPost/login");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setUseCaches(false);
            String request = "username=" + username + "&pwd=" + password;
            httpURLConnection.setRequestProperty("Content-Length", request.length() + "");
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.getOutputStream().write(request.getBytes());
            if (httpURLConnection.getResponseCode() != 200) {
                return request;
            }
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String result = bufferedReader.readLine();
            httpURLConnection.disconnect();
            return result;
        }
        return null;
    }
}
